package dirty

import (
	"bufio"
	"fmt"
	"io"
	"reflect"
)

const DEBUG bool = true // build -X

func debugf(format string, a ...interface{}) {
	if DEBUG {
		fmt.Printf(format, a...)
	}
}
func debugln(a ...interface{}) {
	if DEBUG {
		fmt.Println(a...)
	}
}

// todo func LoadArray()
func Load(r io.Reader) (Array, error) {
	scanner := bufio.NewReader(r)
	array := []Element{}
	comment := token{ttype: COMMENT}
	lbrack := token{ttype: LBRACKET}
	eof := token{ttype: EOF}
	expected := lbrack
	for {
		t, err := nextToken(scanner)
		//debugf("in Load got %+v\n", t)
		if err != nil {
			return []Element{}, err
		}
		if t == comment {
			continue
		} else if t == lbrack {
			if expected != lbrack {
				//debugln("expected lbrac")
				return []Element{}, NewSyntaxError(t, []token{expected})
			}
			//debugf("in Load loading array\n")
			array, err = loadArray(scanner)
			if err != nil {
				return Array{}, err
			}
			expected = eof
		} else if t == eof {
			if expected != eof {
				//debugln("expected eof")
				return []Element{}, NewSyntaxError(t, []token{expected})
			}
			//debugf("in Load eofing\n")
			return array, nil
		} else {
			//debugln("garbage")
			return []Element{}, NewSyntaxError(t, []token{expected})
		}
	}
}

// todo func Load()
func LoadStruct(r io.Reader, s interface{}) error {
	array, err := Load(r)
	if err != nil {
		return err
	}
	v := reflect.ValueOf(s).Elem()
	return convertStruct(array, v)
}
